<template>
	<view style="padding: 20px;">
		<uni-forms ref="articleFormRef" :rules="rules" :model="articleForm">
			<uni-forms-item label="" name="title">
				<uni-easyinput v-model="articleForm.title" placeholder="标题" />
			</uni-forms-item>

			<uni-forms-item label="" name="categoryId">
				<uni-section title="分类" type="line">
					<uni-data-select v-model="articleForm.categoryId" :localdata="categoryList">
					</uni-data-select>
				</uni-section>
			</uni-forms-item>

			<uni-forms-item label="" name="details">
				<editor class="detailsEditor" id="detailsEditor" placeholder="输入正文..." @input="editorInput"></editor>
			</uni-forms-item>

			<button type="primary" @tap="publish">发 布</button>
		</uni-forms>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import baseApi from '@/api/base.js';
	import articleApi from '@/api/article.js'
	import {
		useUserStore
	} from '@/stores/user';
	import storage from '@/utils/storage';

	let userStore = useUserStore();
	const articleFormRef = ref()
	const articleForm = ref({})
	const categoryList = ref([])
	const editorText = ref()

	onLoad(async () => {
		let res = await baseApi.getParamListByBaseName('articleType')
		categoryList.value = res.data.map(item => {
			return {
				value: item.paramValue,
				text: item.paramName
			}
		});
	})

	const editorInput = (input) => {
		articleForm.value.details = input.detail.html;
	}

	const publish = () => {
		articleFormRef.value.validate().then(async res => {
			// console.log(articleForm.value);
			await articleApi.addArticle(articleForm.value)
			articleForm.value = {};
			// 清理表单验证
			articleFormRef.value.clearValidate();
			// 富文本编辑器清理
			uni.createSelectorQuery().select('#detailsEditor').context((res) => {
				res.context.clear()
			}).exec()
			
			uni.showToast({
				title: '分享成功'
			})
			
			setTimeout(function() {
				uni.navigateTo({
					url: '/pages/article/publish-success'
				})
			})
			
		}).catch(err => {
			console.log('err', articleForm.value);
		})
	}

	const rules = ref({
		title: {
			rules: [{
				required: true,
				errorMessage: "请输入标题"
			}]
		},
		categoryId: {
			rules: [{
				required: true,
				errorMessage: "请选择分类"
			}]
		},
		details: {
			rules: [{
				required: true,
				errorMessage: "请输入正文"
			}]
		}
	})
</script>

<style lang="scss">
	.detailsEditor {
		border: 1px solid #e5e5e5;
		padding: 10px;
		border-radius: 5px;
		height: 100vh-45;
	}
</style>